package com.example.daily.ui.auth

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.daily.data.UserPreferences
import com.example.daily.data.dao.UserDao
import com.example.daily.data.entity.User
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class AuthViewModel @Inject constructor(
    private val userDao: UserDao,
    private val userPreferences: UserPreferences
) : ViewModel() {

    private val _authState = MutableStateFlow<AuthState>(AuthState.Initial)
    val authState: StateFlow<AuthState> = _authState

    fun login(username: String, password: String) {
        viewModelScope.launch {
            _authState.value = AuthState.Loading
            try {
                val user = userDao.getUserByUsername(username)
                if (user != null && user.password == password) {
                    userPreferences.saveUserId(user.id)
                    _authState.value = AuthState.Success(user)
                } else {
                    _authState.value = AuthState.Error("用户名或密码错误")
                }
            } catch (e: Exception) {
                _authState.value = AuthState.Error("登录失败: ${e.message}")
            }
        }
    }

    fun register(username: String, password: String) {
        viewModelScope.launch {
            _authState.value = AuthState.Loading
            try {
                val existingUser = userDao.getUserByUsername(username)
                if (existingUser != null) {
                    _authState.value = AuthState.Error("用户名已存在")
                    return@launch
                }

                val user = User(
                    username = username,
                    password = password
                )
                val userId = userDao.insertUser(user)
                val newUser = user.copy(id = userId.toInt())
                userPreferences.saveUserId(newUser.id)
                _authState.value = AuthState.Success(newUser)
            } catch (e: Exception) {
                _authState.value = AuthState.Error("注册失败: ${e.message}")
            }
        }
    }

    fun logout() {
        viewModelScope.launch {
            userPreferences.clearUserId()
            _authState.value = AuthState.Initial
        }
    }

    fun resetState() {
        _authState.value = AuthState.Initial
    }
}

sealed class AuthState {
    object Initial : AuthState()
    object Loading : AuthState()
    data class Success(val user: User) : AuthState()
    data class Error(val message: String) : AuthState()
} 